package com.filldream.sun.core;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

/**
 * HTTP网络请求
 * @author RickSun
 */
public class UrlUtil {


    /**
     * 拼接URL/接口参数
     * @param linkUrl      url/接口
     * @param paramMap     参数Map
     * @return
     * example:  www.baidu.com  {"name","RickSun"}  --> www.baidu.com?name=RickSun
     */
    public static String splicingParam(String linkUrl, Map<String, String> paramMap) {
        StringBuffer url = new StringBuffer();
        if(paramMap.size() > 0) {
            url.append(linkUrl+"?");
        }else {
            url.append(linkUrl);
        }
        Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
        int num = 0;
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            String param = key + "=" + value;
            if(num == 0 || num >= paramMap.size()) {
                url.append(param);
            }else {
                url.append("&" + param );
            }
            num++;
        }
        return url.toString();
    }

    public static String doGet(String url) {
        return doGet(url,null);
    }
    /**
     * POST请求
     * @param url
     * @param param
     * @return
     */
    public static String doGet(String url, Map<String, String> param) {
        StringBuilder builder=new StringBuilder();
        try {
            String path = url;
            if(param != null && !param.isEmpty()){
                path = splicingParam(url, param);
            }
            URL restServiceURL = new URL(path);
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Accept", "application/json;charset=UTF-8");
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("HTTP GET Request Failed with Error code : "
                        + httpConnection.getResponseCode());
            }
            BufferedReader in = new BufferedReader( new InputStreamReader(httpConnection.getInputStream()  ,"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                builder.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * POST 请求
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url,Map<String, String> param) {
        StringBuilder builder=new StringBuilder();
        try {
            String s = splicingParam(url, param);
            URL restServiceURL = new URL(s );
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Accept", "application/json;charset=UTF-8");
//            httpConnection.setRequestProperty("Accept", "application/json");
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            httpConnection.setDoInput(true);
            // Post 请求不能使用缓存
            httpConnection.setUseCaches(false);
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("HTTP POST Request Failed with Error code : "
                        + httpConnection.getResponseCode());
            }
            BufferedReader in = new BufferedReader( new InputStreamReader(httpConnection.getInputStream()  ,"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                builder.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * PIST 请求
     * @param path
     * @param paramJson
     * @return
     */
    public static String doPost(String path,String paramJson){
        String lines=null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");
            //链接地址
            conn.connect();
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            //发送参数
            writer.write(paramJson);
            //清理当前编辑器的左右缓冲区，并使缓冲区数据写入基础流
            writer.flush();
            if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                lines =reader.readLine();//读取请求结果
            } else {
                System.out.println(conn.getResponseMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lines;
    }




}
